<?php

namespace app\api\controller;

use app\admin\model\CouponCodeCategory;
use app\admin\model\CouponCodeCities;
use app\admin\model\CouponCodeGoods;
use app\admin\model\CouponCodeGoodsCategory;
use app\admin\model\OrderList;
use app\admin\model\CouponCodes;
use app\admin\model\CouponTo;
use app\admin\model\ImportType;
use app\admin\model\User;
use app\api\library\ExceptionHandle;
use app\common\controller\Api;
use app\common\library\Sms as Smslib;
use think\Config;
use think\Db;
use think\Request;

/**
 * ThirdCoupon
 */
class Opencoupon extends Api
{
    //测试环境
    protected $url = 'http://pre.openapi.fulu.com/api/getway';
    protected $app_key = 'i4esv1l+76l/7NQCL3QudG90Fq+YgVfFGJAWgT+7qO1Bm9o/adG/1iwO2qXsAXNB';
    protected $AppSecret = '0a091b3aa4324435aab703142518a8f7';
    //生产环境
//    protected $url = 'http://openapi.fulu.com/api/getway';
//    protected $app_key = 'dxuJ7/xGIXsAIFjWPdcryKTLKnLCxvoy39neoESfWWiLDYI/m8CoXl7b4/GBfgjn';
//    protected $AppSecret = '39447679a5884dcaa92f4ffad47724e2';
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    public function _initialize()
    {
        $params = $this->request->post();
        
        if(!isset($params['sign'])||!isset($params['timestamp'])||!isset($params['channel'])){
            $this->error('系统参数错误');
        }
        if (!$params['sign'] || !$params['timestamp']||!isset($params['channel'])) {
            $this->error('系统参数错误');
        }
        //判断权限：通过公钥获取私钥，然后用私钥与传递过来的参数进行签名，然后对比客户端传过来的签名
        $res = Db::name('user')->where(['app_key' => $params['channel']])->find();
        if(empty($res)){
            $this->error('无权限,请检查参数');
        }
        //验证签名
        if (ExceptionHandle::getSign($params,$res['app_secret']) != $params['sign']) {
            $this->error('签名错误,请检查参数');
        }

        $this->user = $res;
        $this->params = $params;
    }

    public function sendNotice($mobile,$msg='余额不足请即时充值'){
        $ret = Smslib::send($mobile, null, 1,'');
        $data = [];
        if($ret){
            $data['mobile'] = $mobile;
            $data['content'] = $msg.json_encode($ret,true);
            $data['status'] = 1;
            $data['createtime'] = time();
            Db::name('sms_send')->insertGetId($data);
        }
    }
    /*
     * 列表
     */
    public function internetCouponList()
    {
        $params = $this->params;
        $data = CouponCodeGoods::where('is_enable', 1)
                  ->order('sort desc ,id desc')
                  ->field('id as goods_id,name,introduction,price,price1,goods_code')
                  ->select(); 
            if ($data) {
                $this->success('获取成功', $data);
            }
            $this->error('请求失败');
    }

    /*
     * 详情
     */
    public function goodsDetail()
    {
        $params = $this->params;
            $good = $data = CouponCodeGoods::where('id', $params['goods_id'])
                ->field('id,name,icon,image,introduction,describe,price,retail_price,price1,coupon_code_class_id')
                ->find();
            $img[0] = $data;
            $data = imgStr($img, 'image');
            $data = imgStr($img, 'icon');

            $this->success('获取成功', $data);
    }


    //手机号 商品id 
    public function recharge(){
       $params = $this->params;
       $num = isset($params['number'])?$params['number']:1;
       if(!$params['goods_id']||!$params['mobile']){
         $this->error('缺少参数错误');
       }
       if(!isset($params['exte_id'])||!$params['exte_id']){
         $this->error('请输入exte_id');
       }
       //判断是否存在exte_id
       $res = Db::name('couponOrder')->where(array('exte_id'=>$params['exte_id'],'user_id'=>$this->user['id']))->find();
       if($res){
         $this->error('已下单,请不要重新提交');
       }
       //获取 商品信息
       $goods = CouponCodeGoods::where('id', $params['goods_id'])->find();
       $order_amount = bcmul($goods['price1'],$num);
       if($this->user['money']< 200){
            //短信提示
            $this->sendNotice($this->user['mobile'],'余额不足请即时充值');
       }
       if($order_amount > $this->user['money']){
         //提醒会员金额不足
         $this->sendNotice($this->user['mobile'],'余额不满足本次充值，请马上处理');
         $this->error('无法下单,账号金额不足');
       }
       //判断用户当前的余额是否小于购买权益的金额
       //$num = $params['num'];
       if(empty($goods)){
         $this->error('商品接入中，敬请期待！');
       }
       switch ($goods['coupon_code_class_id']) {
           case '1': //福禄直充
               //$this->success('福禄直充', $goods);
                $this ->receiveCouponV2($goods,$params['mobile'],$num,$params['exte_id']);
               break;
            case '2': //平安健康
                $this ->salf($goods,$params['mobile'],$num,$params['exte_id']);
               break;
            case '3': //福禄卡密
                $this ->receiveCardV2($goods,$params['mobile'],$num,$params['exte_id']);
               //$this->success('福禄卡密', $goods);
               break;
           default:
                $this->error('充值失败');
               break;
       }
        
    }

    //平安健康
    public function salf($goods,$charge_account,$num = 1,$exte_id = ''){
        $where = [
            'status' => 0,
        ];
        switch ($goods['id']) {
            case 4:
                $where['type'] = 1;
                break;
            case 6:
                $where['type'] = 2;
                break;
            default:
                $this->error('充值失败');
                break;
        }
        $result = Db::name('safeCode')->where($where)->order('id asc')->find();
        if(empty($result)){
           $orderData['status'] = 1;//调用失败
           $result['msg'] = '暂无卡券';
           $result['coupon_code'] = '';
           //$msg = '暂无卡券';
        }else{
            $orderData['status'] = 2;//成功
            //$msg = '领取成功';
            $result['msg'] = '领取成功';
             //启动事务
            Db::startTrans();
            Db::name('safeCode')->where(['coupon_code' => $result['coupon_code']])->update(['status' => 1]);
            $orderData['pay_status'] =  $this->updateMoney($order_amount,$this->user['id']);
        }
        $order_amount = bcmul($goods['price1'],$num);
        //下单
        $orderData['order_no'] = date('YmdHis', time()) . str_pad(5, 0, STR_PAD_LEFT) . rand(1000, 99999);//生成订单号
        $orderData['order_amount'] = $order_amount;
        $orderData['user_id'] = $this->user['id'];
        $orderData['user_mobile'] = $charge_account;
        $orderData['goods_id'] = $goods['id'];
        $orderData['goods_code'] = $goods['goods_code'];
        $orderData['goods_name'] = $goods['name'];
        $orderData['price'] = $goods['price'];
        $orderData['price1'] = $goods['price1'];
        $orderData['cost_price'] = $goods['cost_price'];
        $orderData['retail_price'] = $goods['retail_price'];
        $orderData['exte_id'] = $exte_id;
        $orderData['num'] = $num;
        $orderData['create_time'] = $_SERVER['REQUEST_TIME'];
        $orderData['log'] = json_encode($result);
        $res = OrderList::insert($orderData); //领取订单表 插入数据
        if($res) {
            Db::commit();
            $data = [
                'order_no' => $orderData['order_no'],
                'goods_name' =>$goods['name'],
                'status' =>  $orderData['status'],
                'msg' => $result['msg'],
                'mobile' => $charge_account,
                'card_password' => $result['coupon_code'],
                'create_time' => $orderData['create_time'],
            ];
            $this->success(__('success'), $data);
        }else{
            // 回滚事务
           Db::rollback();
           $this->error('下单失败');
        }
    }

    //福禄直充方法
    public function  receiveCouponV2($goods,$charge_account,$num = 1,$exte_id = ''){

        $postData['app_key'] = $this->app_key;
        $postData['method'] = 'fulu.order.direct.add';
        $postData['timestamp'] = date("Y-m-d H:i:s");
        $postData['version'] = '2.0';
        $postData['format'] = 'json';
        $postData['charset'] = 'utf-8';
        $postData['sign_type'] = 'md5';
        $postData['app_auth_token'] = '';
        $biz_content['customer_order_no'] = date('YmdHis', time()) . str_pad(5, 0, STR_PAD_LEFT) . rand(1000, 99999);//生成订单号
        //$biz_content['product_id'] = $goods['goods_code']; //商品编号
        $biz_content['product_id'] = '10000586'; //标识
        $biz_content['buy_num'] = $num; //充值数量
        $biz_content['charge_account'] = $charge_account; //账户
        $biz_content['charge_ip'] = $this->request->ip();
        $postData['biz_content'] = json_encode($biz_content);
        $postData['sign'] = $this->getSign($postData);
        $result = json_decode(ExceptionHandle::curl_json($this->url,json_encode($postData)), true);
        if ($result['code'] == 0) { //接口调用成功
            $orderData['status'] = 2;//
        } else {
            $orderData['status'] = 1;//调用失败
        }
        $order_amount = bcmul($goods['price1'],$num);
        $orderData['order_no'] = $biz_content['customer_order_no'];
        $orderData['order_amount'] = $order_amount;
        $orderData['user_id'] = $this->user['id'];
        $orderData['user_mobile'] = $charge_account;
        $orderData['goods_id'] = $goods['id'];
        $orderData['goods_code'] = $goods['goods_code'];
        $orderData['goods_name'] = $goods['name'];
        $orderData['price'] = $goods['price'];
        $orderData['price1'] = $goods['price1'];
        $orderData['exte_id'] = $exte_id;
        $orderData['num'] = $num;
        $orderData['create_time'] = $_SERVER['REQUEST_TIME'];
        $orderData['pay_status'] =  $this->updateMoney($order_amount,$this->user['id']);
        //$orderData['end_time'] = time() * 48 * 3600;
        $orderData['log'] = json_encode($result,JSON_FORCE_OBJECT | JSON_UNESCAPED_UNICODE);
        //dump($orderData);exit;
        $res = OrderList::insert($orderData); //领取订单表 插入数据
        if($res) {
            $data = [
                'order_no' => $orderData['order_no'],
                'goods_name' =>$goods['name'],
                'status' =>$orderData['status'],
                'msg' => $result['message'],
                'mobile' => $charge_account,
                'create_time' => $orderData['create_time'],
            ];
            $this->success(__('success'), $data);
        }
    }


    //领取互联网 卡密
    public function  receiveCardV2($goods,$charge_account,$num = 1,$exte_id = ''){

        $postData['app_key'] = $this->app_key;
        $postData['method'] = 'fulu.order.card.add';
        $postData['timestamp'] = date("Y-m-d H:i:s");
        $postData['version'] = '2.0';
        $postData['format'] = 'json';
        $postData['charset'] = 'utf-8';
        $postData['sign_type'] = 'md5';
        $postData['app_auth_token'] = '';
        $biz_content['customer_order_no'] = date('YmdHis', time()) . str_pad(5, 0, STR_PAD_LEFT) . rand(1000, 99999);//生成订单号
        //$biz_content['product_id'] = $goods['goods_code']; //商品编号
        $biz_content['product_id'] = '10000587'; //标识
        $biz_content['buy_num'] = $num; //充值数量
        $biz_content['charge_account'] = $charge_account; //账户
        $biz_content['charge_ip'] = $this->request->ip();
        $postData['biz_content'] = json_encode($biz_content);
        $postData['sign'] = $this->getSign($postData);
        $result = json_decode(ExceptionHandle::curl_json($this->url,json_encode($postData)), true);
        if ($result['code'] == 0) { //接口调用成功
            $orderData['status'] = 2;//
        } else {
            $orderData['status'] = 1;//调用失败
        }
        $order_amount = bcmul($goods['price1'],$num);
        $orderData['order_no'] = $biz_content['customer_order_no'];
        $orderData['order_amount'] = $order_amount;
        $orderData['user_id'] = $this->user['id'];
        $orderData['order_amount'] = bcmul($goods['price1'],$num);
        $orderData['user_mobile'] = $charge_account;
        $orderData['goods_id'] = $goods['id'];
        $orderData['goods_code'] = $goods['goods_code'];
        $orderData['goods_name'] = $goods['name'];
        $orderData['price'] = $goods['price'];
        $orderData['price1'] = $goods['price1'];
        $orderData['exte_id'] = $exte_id;
        $orderData['num'] = $num;
        $orderData['create_time'] = $_SERVER['REQUEST_TIME'];
        $orderData['pay_status'] =  $this->updateMoney($order_amount,$this->user['id']);
        //$orderData['end_time'] = time() * 48 * 3600;
        $orderData['log'] = json_encode($result,JSON_FORCE_OBJECT | JSON_UNESCAPED_UNICODE);

        $res = OrderList::insert($orderData); //领取订单表 插入数据
        if($res) {
            $data = [
                'order_no' => $orderData['order_no'],
                'goods_name' =>$goods['name'],
                'status' =>$orderData['status'],
                'msg' => $result['message'],
                'mobile' => $charge_account,
                'card_password' =>$result['sign'],
                'create_time' => $orderData['create_time'],
            ];
            $this->success(__('success'), $data);
        }
    }

    public function updateMoney($amount,$user_id){
       $user = Db::name('user')->where(['id' => $user_id])->find();
       $balance = bcsub($user['money'],$amount);
       $res = Db::name('user')->where(['id' => $user_id])->data(['money' =>$balance])->update();
       if($res){ //交易日志
            Db::name('trade_log')->data([
                'user_id' => $user_id,
                'before' => $user['money'],
                'money' => '-'.$amount,
                'balance' => $balance,
                'type' => 1,
                'add_time' => time(),
            ])->insert();
       }
       return $res;
    }
    
    /**
     * php签名方法
     */
    public function getSign($Parameters)
    {
        //签名步骤一：把字典json序列化
        $json = json_encode( $Parameters, 320 );
        //签名步骤二：转化为数组
        $jsonArr = preg_split('/(?<!^)(?!$)/u', $json );
        //签名步骤三：排序
        sort( $jsonArr );
        //签名步骤四：转化为字符串
        $string = implode( '', $jsonArr );
        //签名步骤五：在string后加入secret
        $string = $string . $this->AppSecret;
        //签名步骤六：MD5加密
        $result_ = strtolower( md5( $string ) );
        return $result_;
    }

}
